"use strict";
const CONFIG = require('../../../../../common/config');
const moment = require('moment');
const async = require('async');
const YjxApiApplyModel = require('../../../../../common/yjxMysql/mapping/YjxOpenapiAuthModel');
const luaUtil = require('../commonUtils/luaUtil');
const CONSTANT =  require("../../const/CONST");
const EncryptUtil = require('../../../../../common/util/EncryptUtil');

const authorizeUtil = (function () {

    function authorizeUtil() {
    }

    /**
     * 申请 token
     * @author mk
     * @date  2018-5-30
     * @param apiKey      必须   xxxxxx        入驻机构唯一标识
     * @param nonceStr     必须   yyyyyyyyyyy   随机字符串
     * @param expiration  必须   1000          token 有效期, [300, 2592000], 单位: 秒, 300s 到 30 天, 不建议过长
     * @param signature   必须   XXXXXXXXXXXXXX 由前三个参数计算得出
     * @param callback    "token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2"
     */
    authorizeUtil.applyToken = function (apiKey,nonceStr,expiration,signature,callback) {
        let tasks = [];
        //1.查询key和secret的有效性
        tasks.push(function (callback) {
            (new YjxApiApplyModel()).findKeySecretToDb(apiKey,function (DbErr,keyInfo) {
                if (DbErr) {
                    console.log("authorizeUtil applyToken  findKeySecretToDb err" + DbErr);
                    return callback(DbErr, null);
                }
                if (!keyInfo || keyInfo.length <= 0) {
                    return callback(CONSTANT.CODE.PERMISSION_DENIED, null);
                }
                let data = {};
                data.keyInfo = keyInfo[0];
                return callback(null,data);
            });
        });
        //2.通过secret+apiKey+noceStr+expiration生成 signature
        tasks.push(function (data,callback) {
            let sign = EncryptUtil.genOpenApiAuthSign(data.keyInfo.apiSecret,apiKey, expiration, nonceStr);
            console.log("计算得到的 sign"+sign +",传入比对的sign"+ signature);
            data.sign = sign;
            return callback(null,data);
        });
        //3.验证生成的signature 和参数中signature是否一致
        tasks.push(function (data,callback) {
            if (!data.sign){
                return callback(CONSTANT.CODE.UNKNOWN_ERR, null);
            }
            if (data.sign != signature){
                return callback(CONSTANT.CODE.INVALID_PARAMS, null);
            }
            return callback(null,data);
        });
        //4.生成token加入redis
        tasks.push(function (data,callback) {
            let curTime = Date.parse(new Date())/1000;
            let expire = expiration - curTime  ;
            EncryptUtil.genOpenApiAuthToken(apiKey, data.keyInfo.apiSecret, data.keyInfo.userId, expire,function (err,result) {
                if (err){
                    console.log("genOpenApiAuthToken err" + err);
                    return callback(CONSTANT.CODE.UNKNOWN_ERR,null);
                }
                data.token = result.token;
                luaUtil.setApiKeyAndToken(data.keyInfo,data.token,expire, function (luaErr, token) {
                    if (luaErr) {
                        console.log("authorizeUtil applyToken setApiKeyAndToken err" + luaErr);
                        return callback(CONSTANT.CODE.UNKNOWN_ERR, null);
                    }
                    if (!token){
                        return callback(CONSTANT.CODE.UNKNOWN_ERR,null);
                    }
                    data.token = token;
                    return callback(null,data);
                });
            });
        });
        //返回生成的token
        async.waterfall(tasks, function (error, data) {
            if(error) {
                console.log("applyToken error"+error);
                return callback(error, null);
            }
            return callback(null, {token : data.token});
        });
    };


    /**
     * 查询 token 信息
     * @author mk
     * @date   2018-5-30
     * @param apiKey  必须   xxxxxx      入驻机构唯一标识
     * @param token    必须   eyJ0eXA...  要查询的 token返回数据
     * @param callback  "token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2"
     *                  "expiry_time" : 1513549  过期时间戳
     */
    authorizeUtil.queryToken= function (apiKey,token,callback) {
        //调用lua查询redis缓存数据
        luaUtil.queryCurrentToken(apiKey,token, function (luaErr, expireTime) {
            if (luaErr) {
                console.log("authorizeUtil applyToken setApiKeyAndToken err" + luaErr);
                return callback(CONSTANT.CODE.UNKNOWN_ERR, null);
            }
            if (!expireTime) {
                return callback(CONSTANT.CODE.UNKNOWN_ERR, null);
            }
            let data = {};
            data.token = token;
            data.expiry_time = expireTime;
            return callback(null,data);
        });
    };


    return authorizeUtil;
})();

module.exports = authorizeUtil;